package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.dto.RoleDto;
import com.xxx.dto.UserDto;
import com.xxx.pojo.*;
import com.xxx.service.MenuService;
import com.xxx.service.RoleMenuService;
import com.xxx.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/role")
@RestController
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private MenuService menuService;

    @Transactional
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('sys:add:role')")
    public Result addRole(@RequestBody RoleDto roleDto){
        if (Objects.isNull(roleDto)){
            throw new RuntimeException("请求格式错误！");
        }
        List<Menu> menus = roleDto.getMenus();
        Role role = new Role();
        BeanUtils.copyProperties(roleDto,role);
        LocalDate now = LocalDate.now();
        role.setCreateTime(now);
        role.setUpdateTime(now);
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        role.setCreateUser(loginUser.getUser().getName());
        role.setUpdateUser(loginUser.getUser().getName());
        boolean save = roleService.save(role);
        if (menus != null && menus.size()>0){
            for (Menu menu : menus) {
                RoleMenu roleMenu = new RoleMenu(role.getRoleId(), menu.getMenuId(), null, null);
                roleMenuService.save(roleMenu);
            }
        }
        if (!save){
            throw new RuntimeException("添加角色失败！");
        }
        return Result.success("添加角色成功!");
    }

    @PreAuthorize("hasAnyAuthority('sys:select:role')")
    @GetMapping("/selectAll")
    public Result selectAll(){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getStatus, 0);
        List<Role> list = roleService.list(wrapper);
        return Result.success("",list);
    }


    @PreAuthorize("hasAnyAuthority('sys:select:role')")
    @PostMapping("/select")
    public Result selectRoleByCondition(@RequestBody Role role, @RequestParam("current") Integer current, @RequestParam("size") Integer size){
        if (Objects.isNull(role)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        if (role.getStatus() == null || role.getStatus().getI() == 2){
            role.setStatus(null);
        }
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(role.getRoleName() != null && role.getRoleName().length()>0,Role::getRoleName,role.getRoleName())
                .like(role.getRoleId() != null && role.getRoleId() >= 0,Role::getRoleId,role.getRoleId())
                .like(role.getRemark() != null && role.getRemark().length()>0,Role::getRemark,role.getRemark())
                .eq(role.getStatus() != null,Role::getStatus,role.getStatus())
                .eq(Role::getDelete,0);
        IPage iPage = new Page(current,size);
        IPage page = roleService.page(iPage,wrapper);
        List<Role> roles = page.getRecords();
        List<RoleDto> list = roles.stream().map(o -> {
            List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, o.getRoleId()).eq(RoleMenu::getStatus, 0));

            List<Menu> menus = new ArrayList<>();
            if (roleMenus != null) {
                for (RoleMenu roleMenu : roleMenus) {
                    Menu one = menuService.getOne(new LambdaQueryWrapper<Menu>().eq(roleMenu.getMenuId() != null && roleMenu.getMenuId() > 0, Menu::getMenuId, roleMenu.getMenuId()));
                    menus.add(one);
                }
            }
            RoleDto roleDto = new RoleDto();
            BeanUtils.copyProperties(o, roleDto);
            roleDto.setMenus(menus);
            return roleDto;
        }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total", page.getTotal());
        return Result.success("",map);
    }

    @PreAuthorize("hasAnyAuthority('sys:update:role')")
    @Transactional
    @PutMapping("/update")
    public Result updateRoleById(@RequestBody RoleDto roleDto){
        if (Objects.isNull(roleDto)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        List<Menu> menus = roleDto.getMenus();
        Role role = new Role();
        BeanUtils.copyProperties(roleDto,role);
        if (menus.size()>0){
            boolean update = roleMenuService.update(new LambdaUpdateWrapper<RoleMenu>().set(RoleMenu::getStatus, 1).eq(RoleMenu::getRoleId, role.getRoleId()));
            System.out.println(role.getRoleId());
            for (Menu menu : menus) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getRoleId());
                roleMenu.setMenuId(menu.getMenuId());
                roleMenuService.save(roleMenu);

            }
        }else {
            boolean update = roleMenuService.update(new LambdaUpdateWrapper<RoleMenu>().set(RoleMenu::getStatus, 1).eq(RoleMenu::getRoleId, role.getRoleId()));
        }
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        role.setUpdateUser(loginUser.getUser().getName());
        role.setUpdateTime(LocalDate.now());
        boolean b = roleService.updateById(role);
        if (!b){
            throw new RuntimeException("修改角色失败！");
        }
        return Result.success("修改角色成功!");
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAnyAuthority('sys:delete:role')")
    public Result deleteRoleByIds(@RequestBody List<String> roleIds){
        boolean b = false;
        if (!Objects.isNull(roleIds)){
            for (String roleIdString : roleIds) {
                Long roleId = Long.parseLong(roleIdString);
                b = roleService.removeById(roleId);
                roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(roleId != null && roleId > 0,RoleMenu::getRoleId,roleId));
            }
        }
        if (!b){
            throw new RuntimeException("删除角色失败！");
        }
        return Result.success("删除角色成功!");
    }
}
